package agu.json;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.Collection;
import java.util.List;

@SuppressWarnings("unchecked")
public class JSONArray2 extends JSONArray implements $JSON<Integer>
{
    /** values */
    final List<Object> content;

    public JSONArray2(){
        super();
        content = JSONUtil.getField(this, JSONArray.class, List.class);
    }

    public JSONArray2(Object input){
        this();
        if(input instanceof CharSequence){
            input = new JSONTokener(input.toString());
        }
        if(input instanceof JSONTokener){
            try{
                Object next = ((JSONTokener)input).nextValue();
                input = (JSONArray)next;
            }catch(Exception ex){
                ex.printStackTrace();
                return;
            }
        }
        if(input instanceof Collection){
            content.addAll((Collection<?>)input);
            return;
        }
        content.addAll(JSONUtil.toList(input));
    }

    public JSONArray2 forEach(JSONUtil.EachCallback<JSONArray2, Integer> callback){
        JSONUtil.forEach(this, callback);
        return this;
    }

    /** 除去{@link JSONObject#NULL} */
    public JSONArray2 trim(){
        for(int key = 0; key < length(); key++){
            if(isNull(key)){
                remove(key);
            }
        }
        return this;
    }

    @Override
    public String toString(int indentSpaces){
        try{
            return super.toString(indentSpaces);
        }catch(Exception e){
            return "";
        }
    }

    @Override
    public Object opt(Integer index){
        return super.opt(index);
    }

    @Override
    public JSONArray2 put(Integer index, Object value){
        try{
            super.put(index, value);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return this;
    }

    @Override
    public JSONArray2 put(int index, Object value){
        try{
            super.put(index, value);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return this;
    }
}
